"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Upload, FileText, AlertCircle, CheckCircle } from "lucide-react"

interface ImportDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onImport: (data: any[], format: string) => Promise<void>
}

export function ImportDialog({ open, onOpenChange, onImport }: ImportDialogProps) {
  const [importData, setImportData] = useState("")
  const [format, setFormat] = useState("json")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target?.result as string
      setImportData(content)
      setError(null)
    }
    reader.readAsText(file)
  }

  const validateJsonData = (data: any[]): string | null => {
    if (!Array.isArray(data)) {
      return "数据必须是数组格式"
    }

    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (!item.name) {
        return `第${i + 1}行：姓名不能为空`
      }
      if (typeof item.name !== 'string') {
        return `第${i + 1}行：姓名必须是字符串`
      }
    }

    return null
  }

  const parseCsvData = (csvText: string): any[] => {
    const lines = csvText.split('\n').filter(line => line.trim())
    if (lines.length < 2) {
      throw new Error("CSV文件至少需要包含表头和数据行")
    }

    const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
    const data = []

    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(',').map(v => v.trim().replace(/"/g, ''))
      const item: any = {}
      
      headers.forEach((header, index) => {
        const value = values[index] || ''
        switch (header) {
          case '姓名':
            item.name = value
            break
          case '电话':
            item.phone = value
            break
          case '邮箱':
            item.email = value
            break
          case '公司':
            item.company = value
            break
          case '职位':
            item.position = value
            break
          case '地址':
            item.address = value
            break
          case '分组':
            item.group = value || '默认'
            break
          case '标签':
            item.tags = value ? value.split(';').map((tag: string) => tag.trim()) : []
            break
          case '生日':
            item.birthday = value
            break
          case '备注':
            item.notes = value
            break
          case '收藏':
            item.is_favorite = value === '是' || value === 'true'
            break
        }
      })
      
      if (item.name) {
        data.push(item)
      }
    }

    return data
  }

  const handleImport = async () => {
    if (!importData.trim()) {
      setError("请输入要导入的数据")
      return
    }

    setLoading(true)
    setError(null)
    setSuccess(null)

    try {
      let data: any[]

      if (format === 'json') {
        try {
          data = JSON.parse(importData)
        } catch (e) {
          throw new Error("JSON格式错误，请检查数据格式")
        }
        
        const validationError = validateJsonData(data)
        if (validationError) {
          throw new Error(validationError)
        }
      } else if (format === 'csv') {
        data = parseCsvData(importData)
      } else {
        throw new Error("不支持的格式")
      }

      if (data.length === 0) {
        throw new Error("没有找到有效的数据")
      }

      await onImport(data, format)
      setSuccess(`成功导入 ${data.length} 个联系人`)
      
      // 清空数据
      setImportData("")
      
      // 延迟关闭对话框
      setTimeout(() => {
        onOpenChange(false)
        setSuccess(null)
      }, 2000)

    } catch (err: any) {
      setError(err.message || "导入失败")
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    setImportData("")
    setError(null)
    setSuccess(null)
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>导入联系人</DialogTitle>
          <DialogDescription>
            支持导入JSON和CSV格式的联系人数据
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 格式选择 */}
          <div className="space-y-2">
            <Label>导入格式</Label>
            <Select value={format} onValueChange={setFormat}>
              <SelectTrigger>
                <SelectValue placeholder="选择格式" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="json">JSON格式</SelectItem>
                <SelectItem value="csv">CSV格式</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 文件上传 */}
          <div className="space-y-2">
            <Label>上传文件</Label>
            <div className="flex items-center gap-2">
              <Input
                type="file"
                accept={format === 'json' ? '.json' : '.csv'}
                onChange={handleFileUpload}
                className="flex-1"
              />
              <Upload className="h-4 w-4 text-muted-foreground" />
            </div>
          </div>

          {/* 数据输入 */}
          <div className="space-y-2">
            <Label>或直接粘贴数据</Label>
            <Textarea
              value={importData}
              onChange={(e) => setImportData(e.target.value)}
              placeholder={format === 'json' 
                ? '请粘贴JSON格式数据，例如：\n[\n  {\n    "name": "张三",\n    "phone": "13800138000",\n    "email": "zhangsan@example.com"\n  }\n]'
                : '请粘贴CSV格式数据，第一行为表头，例如：\n姓名,电话,邮箱,公司\n张三,13800138000,zhangsan@example.com,ABC公司'
              }
              rows={8}
              className="font-mono text-sm"
            />
          </div>

          {/* 格式说明 */}
          <Alert>
            <FileText className="h-4 w-4" />
            <AlertDescription>
              {format === 'json' ? (
                <div>
                  <p className="font-medium mb-1">JSON格式要求：</p>
                  <ul className="text-sm space-y-1">
                    <li>• 数据必须是数组格式</li>
                    <li>• 每个联系人对象必须包含 name 字段</li>
                    <li>• 支持字段：name, phone, email, company, position, address, group, tags, birthday, notes, is_favorite</li>
                    <li>• tags 字段为字符串数组</li>
                  </ul>
                </div>
              ) : (
                <div>
                  <p className="font-medium mb-1">CSV格式要求：</p>
                  <ul className="text-sm space-y-1">
                    <li>• 第一行必须是表头</li>
                    <li>• 支持表头：姓名, 电话, 邮箱, 公司, 职位, 地址, 分组, 标签, 生日, 备注, 收藏</li>
                    <li>• 标签字段用分号(;)分隔多个标签</li>
                    <li>• 收藏字段：是/true 表示收藏，否/false 表示不收藏</li>
                  </ul>
                </div>
              )}
            </AlertDescription>
          </Alert>

          {/* 错误提示 */}
          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {/* 成功提示 */}
          {success && (
            <Alert>
              <CheckCircle className="h-4 w-4" />
              <AlertDescription>{success}</AlertDescription>
            </Alert>
          )}
        </div>

        <DialogFooter>
          <Button type="button" variant="outline" onClick={handleClose}>
            取消
          </Button>
          <Button onClick={handleImport} disabled={loading || !importData.trim()}>
            {loading ? "导入中..." : "导入"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
